//
//  LaunchIntroductionView.m
//  YGWLaunchIntroductionDemo
//
//  Created by YuGuowe on 16/4/7.
//  Copyright © 2016年 YuGuowe. All rights reserved.
//

#import "LaunchIntroductionView.h"

static NSString *const kAppVersion = @"appVersion";

@interface LaunchIntroductionView ()<UIScrollViewDelegate>
{
    UIScrollView  *launchScrollView;
    UIPageControl *page;
}
    
@property (nonatomic, copy) EnterBlock enterBlock;

@end

@implementation LaunchIntroductionView
NSArray *images;
BOOL isScrollOut;//在最后一页再次滑动是否隐藏引导页
CGRect enterBtnFrame;
NSString *enterBtnImage;
static LaunchIntroductionView *launch = nil;
#pragma mark - 创建对象-->>不带button
+(instancetype)sharedWithImages:(NSArray *)imageNames{
    images = imageNames;
    isScrollOut = YES;
    launch = [[LaunchIntroductionView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT)];
    launch.backgroundColor = [UIColor whiteColor];
    return launch;
}

#pragma mark - 创建对象-->>带button
+(instancetype)sharedWithImages:(NSArray *)imageNames buttonImage:(NSString *)buttonImageName enterBlock:(EnterBlock)enterBlock {
    launch = [LaunchIntroductionView sharedWithImages:imageNames buttonImage:buttonImageName buttonFrame:CGRectMake(KSCREENWIDTH/2 - 551/4, KSCREENHEIGHT - 150, 551/2, 45) enterBlock:enterBlock];
    return launch;
}
    
+(instancetype)sharedWithImages:(NSArray *)imageNames buttonImage:(NSString *)buttonImageName buttonFrame:(CGRect)frame enterBlock:(EnterBlock)enterBlock{
    images = imageNames;
    isScrollOut = NO;
    enterBtnFrame = frame;
    enterBtnImage = buttonImageName;
    launch = [[LaunchIntroductionView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT)];
    launch.enterBlock = enterBlock;
    launch.backgroundColor = [UIColor whiteColor];
    return launch;
}
#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addObserver:self forKeyPath:@"currentColor" options:NSKeyValueObservingOptionNew context:nil];
        [self addObserver:self forKeyPath:@"nomalColor" options:NSKeyValueObservingOptionNew context:nil];
//        if ([self isFirstLauch]) {
            UIWindow *window = [[UIApplication sharedApplication] windows].lastObject;
            [window addSubview:self];
            [self addImages];
//        }else{
//            [self removeFromSuperview];
//        }
    }
    return self;
}
#pragma mark - 判断是不是首次登录或者版本更新
-(BOOL)isFirstLauch
{
    //获取当前版本号
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentAppVersion = infoDic[@"CFBundleShortVersionString"];
    //获取上次启动应用保存的appVersion
    NSString *version = [[NSUserDefaults standardUserDefaults] objectForKey:kAppVersion];
    //版本升级或首次登录
    if (version == nil || ![version isEqualToString:currentAppVersion]) {
        [[NSUserDefaults standardUserDefaults] setObject:currentAppVersion forKey:kAppVersion];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    }else{
        return NO;
    }
}
#pragma mark - 添加引导页图片
-(void)addImages{
    [self createScrollView];
}
#pragma mark - 创建滚动视图
-(void)createScrollView{
    launchScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT)];
    launchScrollView.showsHorizontalScrollIndicator = NO;
    launchScrollView.bounces = NO;
    launchScrollView.pagingEnabled = YES;
    launchScrollView.delegate = self;
    launchScrollView.contentSize = CGSizeMake(KSCREENWIDTH * images.count, KSCREENHEIGHT);
    [self addSubview:launchScrollView];
    for (int i = 0; i < images.count; i ++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * KSCREENWIDTH, 0, KSCREENWIDTH, KSCREENHEIGHT)];
        imageView.image = [UIImage imageNamed:images[i]];
        [launchScrollView addSubview:imageView];
        //        if (i == images.count - 1) {
        //判断要不要添加button
        //        if (!isScrollOut) {
        //            UIButton *enterButton = [[UIButton alloc] initWithFrame:CGRectMake(enterBtnFrame.origin.x, enterBtnFrame.origin.y, enterBtnFrame.size.width, enterBtnFrame.size.height)];
        if (!isScrollOut) {
            
            UIButton *enterButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 170, 50)];
            enterButton.center = CGPointMake(KSCREENWIDTH * 0.5, KSCREENHEIGHT * 0.89);
            enterButton.backgroundColor = [UIColor clearColor];
            //            UIButton *enterButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150, 30)];
            
            //            [enterButton setTitle:@"立即体验" forState:UIControlStateNormal];
            [enterButton setTitleColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5] forState:UIControlStateNormal];
            enterButton.titleLabel.font = [UIFont systemFontOfSize: 15.0];
            //                [enterButton setImage:[UIImage imageNamed:enterBtnImage] forState:UIControlStateNormal];
            // 按钮边框宽度
//            enterButton.layer.borderWidth = 1.5;
            // 设置圆角
//            enterButton.layer.cornerRadius = 4.5;
            // 设置颜色空间为rgb，用于生成ColorRef
            
//            CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
            // 新建一个红色的ColorRef，用于设置边框（四个数字分别是 r, g, b, alpha）
//            CGColorRef borderColorRef = CGColorCreate(colorSpace,(CGFloat[]){ 0, 0, 0, 0.5 });
            // 设置边框颜色
//            enterButton.layer.borderColor = borderColorRef;
            
            //                [enterButton.layer setBorderWidth:1];
            [enterButton.layer setMasksToBounds:YES];
            
            
            
            [enterButton addTarget:self action:@selector(enterBtnClick) forControlEvents:UIControlEventTouchUpInside];
            [imageView addSubview:enterButton];
            imageView.userInteractionEnabled = YES;
        }
        //        }
    }
    page = [[UIPageControl alloc] initWithFrame:CGRectMake(0, KSCREENHEIGHT - 50, KSCREENWIDTH, 30)];
    page.numberOfPages = images.count;
    page.pageIndicatorTintColor = [UIColor clearColor];
    page.currentPageIndicatorTintColor = [UIColor clearColor];
    page.backgroundColor = [UIColor clearColor];
    page.currentPage = 0;
    page.defersCurrentPageDisplay = YES;
    [self addSubview:page];
}
#pragma mark - 进入按钮
-(void)enterBtnClick{
    [self hideGuidView];
    if (self.enterBlock) {
        self.enterBlock();
    }
}
#pragma mark - 隐藏引导页
-(void)hideGuidView{
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self removeFromSuperview];
        });
        
    }];
}
#pragma mark - scrollView Delegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    int cuttentIndex = (int)(scrollView.contentOffset.x + KSCREENWIDTH/2)/KSCREENWIDTH;
    if (cuttentIndex == images.count - 1) {
        if ([self isScrolltoLeft:scrollView]) {
            if (!isScrollOut) {
                return ;
            }
            [self hideGuidView];
        }
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == launchScrollView) {
        int cuttentIndex = (int)(scrollView.contentOffset.x + KSCREENWIDTH/2)/KSCREENWIDTH;
        page.currentPage = cuttentIndex;
    }
}

#pragma mark - 判断滚动方向
-(BOOL )isScrolltoLeft:(UIScrollView *) scrollView{
    //返回YES为向左反动，NO为右滚动
    if ([scrollView.panGestureRecognizer translationInView:scrollView.superview].x < 0) {
        return YES;
    }else{
        return NO;
    }
}

#pragma mark - KVO监测值的变化
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"currentColor"]) {
        page.currentPageIndicatorTintColor = self.currentColor;
    }
    if ([keyPath isEqualToString:@"nomalColor"]) {
        page.pageIndicatorTintColor = self.nomalColor;
    }
}

@end
